package com.yicoollxing.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.yicoollxing.service.IFileService;
import com.yicoollxing.util.FTPUtil;


@Service("iFileService")
public class FileServiceImpl implements IFileService {
     
	private static Logger logger=LoggerFactory.getLogger(FileServiceImpl.class);
	public String   upload(MultipartFile file,String  path){
		
		String fileName=file.getOriginalFilename();
		String fileExtansionName=fileName.substring(fileName.lastIndexOf("."));
		String uploadFileName=UUID.randomUUID().toString()+fileExtansionName;
		File fileDir=new File(path);
		if(!fileDir.exists()){
			fileDir.setWritable(true);
			fileDir.mkdirs();
		}
		File targetFile=new File(fileDir,uploadFileName);
		try {
			file.transferTo(targetFile);
			//文件上传成功
			//todo  将targetFile 上传到ftp服务器
			if(FTPUtil.uploadFile(Lists.newArrayList(targetFile))){
				//todo 上传完成后删除upload下的文件
				targetFile.delete();
			}else{
				return null;
			}
			
			
		} catch (IllegalStateException | IOException e) {
			logger.error("上传文件异常", e);
            return null;
		}
		return targetFile.getName();
	}
}
